package com.blq.developtools.activity;

import android.view.LayoutInflater;
import android.view.View;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blq.developtools.R;
import com.blq.developtools.adapter.ViewPropertiesAdapter;
import com.blq.developtools.bean.ViewTreeBean;
import com.blq.developtools.interfaces.OnLayoutStructureSelectListener;
import com.blq.developtools.observerpattern.observable.LayoutViewerObservable;
import com.blq.developtools.observerpattern.observer.ILayoutViewerActionObserve;
import com.blq.developtools.service.DevelopToolsService;
import com.blq.developtools.utils.DevelopUtils;
import com.blq.developtools.view.LayoutStructureView;

import java.util.ArrayList;
import java.util.List;

import blq.ssnb.baseconfigure.BaseActivity;
import blq.ssnb.snbview.listener.OnIntervalClickListener;

/**
 * <pre>
 * ****************************************************************
 * 文件名称:LayoutViewerActivity.java
 * 作 者:SSNB
 * 创建时间:2024/5/14
 * 文件描述:
 * 注意事项:
 * 版权声明:Copyright (C) 2015-2025 杭州中焯信息技术股份有限公司
 * 修改历史:2024/5/14 1.00 初始版本
 * ****************************************************************
 * </pre>
 */
public class LayoutViewerActivity extends BaseActivity {
    private LayoutStructureView layoutStructureView;

    // <editor-fold defaultstate="collapsed" desc="属性展示框">
    private View layoutInfoView;
    private TextView currentParamsTitle;
    private View propertyCloseBtn;
    private RecyclerView layoutPropertiesList;
    private ViewPropertiesAdapter propertiesAdapter;

    private View toParentViewBtn;
    private View toPreViewBtn;
    private View toNextViewBtn;
    private View toChildViewBtn;
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="多布局选择框">

    private View selectRootView;
    private TextView selectTitleView;
    private View selectCloseBtn;
    private LinearLayout selectContainerLayout;


    // </editor-fold>

    private List<ViewTreeBean> linearTreeBean;

    private ILayoutViewerActionObserve observe = new ILayoutViewerActionObserve() {
        @Override
        public void onLayoutInspectorStatus(boolean isOpen) {
            if (!isOpen) {
                getActivity().finish();
            }
        }

        @Override
        public void onLayoutViewerStatus(boolean isOpen) {

        }

        @Override
        public void onLayoutViewerStatusChange(LayoutViewerStatus status) {
            switch (status) {
                case STATUS_VIEW_PROPERTIES:
                    selectRootView.setVisibility(View.GONE);
                    layoutInfoView.setVisibility(View.VISIBLE);
                    break;
                case STATUS_SELECT_VIEW:
                    selectRootView.setVisibility(View.VISIBLE);
                    layoutInfoView.setVisibility(View.GONE);
                    break;
                case STATUS_NORMAL:
                    selectRootView.setVisibility(View.GONE);
                    layoutInfoView.setVisibility(View.GONE);
                    break;
            }
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        LayoutViewerObservable.getInstance().onLayoutViewerStatus(false);

    }

    @Override
    protected int contentView() {
        LayoutViewerObservable.getInstance().onLayoutViewerStatus(true);
        return R.layout.activity_layout_inspector;
    }

    @Override
    protected void initView() {
        layoutStructureView = findViewById(R.id.lsv_layout_structure_canvas);

        layoutInfoView = findViewById(R.id.ll_layout_info_root_view);
        currentParamsTitle = findViewById(R.id.tv_view_title);
        propertyCloseBtn = findViewById(R.id.btn_properties_close);
        layoutPropertiesList = findViewById(R.id.rv_view_properties);
        layoutPropertiesList.setLayoutManager(new LinearLayoutManager(this));
        propertiesAdapter = new ViewPropertiesAdapter(this);
        layoutPropertiesList.setAdapter(propertiesAdapter);

        toParentViewBtn = findViewById(R.id.btn_to_parent_view);
        toPreViewBtn = findViewById(R.id.btn_to_pre_view);
        toNextViewBtn = findViewById(R.id.btn_to_next_view);
        toChildViewBtn = findViewById(R.id.btn_to_child_view);

        selectRootView = findViewById(R.id.ll_layout_select_item_root_view);
        selectTitleView = findViewById(R.id.tv_select_title);
        selectCloseBtn = findViewById(R.id.btn_select_close);
        selectContainerLayout = findViewById(R.id.ll_select_view_container);

    }

    @Override
    protected void bindData() {
        AccessibilityNodeInfo rootParent = getIntent().getParcelableExtra("xx");
        linearTreeBean = new ArrayList<>();
        ViewTreeBean bean = analysisViewTree(rootParent, 1, 0, linearTreeBean);
        doprintln(bean);
        if (bean != null) {
            layoutStructureView.setLayoutTree(bean);
        }
    }

    @Override
    protected void operation() {
        super.operation();
        LayoutViewerObservable.getInstance().registerNotify(observe);
    }

    private ViewTreeBean analysisViewTree(AccessibilityNodeInfo nodeInfo, int layerLevel, int inParentLayerLevel, List<ViewTreeBean> linearTreeBean) {
        if (nodeInfo != null) {
            if (!nodeInfo.isVisibleToUser()) {
                return null;
            }
            ViewTreeBean bean = new ViewTreeBean();
            bean.setViewIDName(nodeInfo.getViewIdResourceName());
            bean.setClassType(DevelopUtils.unNullBean(nodeInfo.getClassName(), "未获取ClassType").toString());
            bean.setText(DevelopUtils.unNullBean(nodeInfo.getText(), "").toString());
            nodeInfo.getBoundsInScreen(bean.getInScreenLocation());
            nodeInfo.getBoundsInParent(bean.getInParentLocation());
            bean.setPackageName(DevelopUtils.unNullBean(nodeInfo.getPackageName(), "未获取包名").toString());
            ;
            bean.setContentDescription(DevelopUtils.unNullBean(nodeInfo.getContentDescription(), "").toString());
            bean.setLayerLevel(layerLevel);
            bean.setInParentLevel(inParentLayerLevel);
            bean.setParentView(null);

            bean.isVisibleToUser = nodeInfo.isVisibleToUser();
            bean.isClickable = nodeInfo.isClickable();
            bean.isLongClickable = nodeInfo.isLongClickable();
            bean.isEnable = nodeInfo.isEnabled();
            bean.isFocusable = nodeInfo.isFocusable();
            bean.isFocused = nodeInfo.isFocused();
            bean.isCheckable = nodeInfo.isCheckable();
            bean.isChecked = nodeInfo.isChecked();
            bean.isScrollable = nodeInfo.isScrollable();
            bean.isEditable = nodeInfo.isEditable();
            bean.isSelected = nodeInfo.isSelected();
            bean.isPassword = nodeInfo.isPassword();
            linearTreeBean.add(bean);
            List<ViewTreeBean> childList = new ArrayList<>();
            int childIndex = 0;
            for (int i = 0; i < nodeInfo.getChildCount(); i++) {
                AccessibilityNodeInfo childNodeInfo = nodeInfo.getChild(i);
                ViewTreeBean treeBean = analysisViewTree(childNodeInfo, layerLevel + 1, childIndex + 1, linearTreeBean);
                if (treeBean != null) {
                    treeBean.setParentView(bean);
                    childList.add(treeBean);
                    childIndex++;
                }
            }
            bean.setChildView(childList);
            return bean;
        }
        return null;
    }

    @Override
    protected void bindEvent() {
        layoutStructureView.setOnLayoutStructureSelectListener(containsBeans -> {
            if (containsBeans.size() == 1) {
                showViewInfo(containsBeans.get(0));
            } else if (!containsBeans.isEmpty()) {
                showViewSelect(containsBeans);
            } else {
                layoutStructureView.setSelectLayout(null);
            }
        });
        selectCloseBtn.setOnClickListener(new OnIntervalClickListener() {
            @Override
            public void onEffectiveClick(View v) {
                LayoutViewerObservable.getInstance().onLayoutViewerStatusChange(ILayoutViewerActionObserve.LayoutViewerStatus.STATUS_NORMAL);
            }
        });
        propertyCloseBtn.setOnClickListener(new OnIntervalClickListener() {
            @Override
            public void onEffectiveClick(View v) {
                LayoutViewerObservable.getInstance().onLayoutViewerStatusChange(ILayoutViewerActionObserve.LayoutViewerStatus.STATUS_NORMAL);
            }
        });
        toParentViewBtn.setOnClickListener(new OnIntervalClickListener() {
            @Override
            public void onEffectiveClick(View v) {
                if (v.getVisibility() == View.VISIBLE) {
                    ViewTreeBean bean = layoutStructureView.getSelectLayout();
                    if (bean != null) {
                        ViewTreeBean parent = bean.getParentView();
                        if (parent != null) {
                            showViewInfo(parent);
                        } else {
                            updateActionAble(bean);
                        }
                    }
                }
            }
        });
        toPreViewBtn.setOnClickListener(new OnIntervalClickListener() {
            @Override
            public void onEffectiveClick(View v) {
                switchLayout(true);
            }
        });
        toNextViewBtn.setOnClickListener(new OnIntervalClickListener() {
            @Override
            public void onEffectiveClick(View v) {
                switchLayout(false);
            }
        });
        toChildViewBtn.setOnClickListener(new OnIntervalClickListener() {
            @Override
            public void onEffectiveClick(View v) {
                if (v.getVisibility() == View.VISIBLE) {
                    ViewTreeBean bean = layoutStructureView.getSelectLayout();
                    if (bean != null) {
                        if (!bean.getChildView().isEmpty()) {
                            ViewTreeBean newBean = bean.getChildView().get(0);
                            showViewInfo(newBean);
                        } else {
                            updateActionAble(bean);
                        }
                    }
                }
            }
        });

        propertiesAdapter.setListener(this::showViewInfo);
    }

    private void switchLayout(boolean isPreView) {
        ViewTreeBean bean = layoutStructureView.getSelectLayout();
        if (bean != null) {
            int index = linearTreeBean.indexOf(bean);
            if (index != -1 && !linearTreeBean.isEmpty()) {
                if (isPreView) {
                    index -= 1;
                } else {
                    index += 1;
                }
                if (index < 0) {
                    index = linearTreeBean.size() - 1;
                } else if (index >= linearTreeBean.size()) {
                    index = 0;
                }
                ViewTreeBean newBean = linearTreeBean.get(index);
                showViewInfo(newBean);
            }
        }
    }

    private void showViewSelect(List<ViewTreeBean> containsBeans) {
        LayoutViewerObservable.getInstance().onLayoutViewerStatusChange(ILayoutViewerActionObserve.LayoutViewerStatus.STATUS_SELECT_VIEW);
        selectTitleView.setText(containsBeans.size() + "个View可选");
        insertSelectView(containsBeans);
    }

    private void insertSelectView(List<ViewTreeBean> containsBeans) {
        selectContainerLayout.removeAllViews();
        for (int i = 0; i < containsBeans.size(); i++) {
            final ViewTreeBean bean = containsBeans.get(i);
            View view = LayoutInflater.from(this).inflate(R.layout.item_select_view, selectContainerLayout, false);
            ((TextView) view.findViewById(R.id.tv_index_view)).setText((i + 1) + "");
            ((TextView) view.findViewById(R.id.tv_class_name)).setText(bean.getClassType());
            ((TextView) view.findViewById(R.id.tv_child_count)).setText(bean.getChildView().size() + "个Child");
            view.setOnClickListener(v -> {
                selectRootView.setVisibility(View.GONE);
                layoutStructureView.setSelectLayout(bean);
                showViewInfo(bean);
            });

            selectContainerLayout.addView(view);

        }
    }

    private void showViewInfo(ViewTreeBean viewTreeBean) {
        LayoutViewerObservable.getInstance().onLayoutViewerStatusChange(ILayoutViewerActionObserve.LayoutViewerStatus.STATUS_VIEW_PROPERTIES);
        currentParamsTitle.setText(viewTreeBean.getViewIDName() + " 属性列表");
        layoutStructureView.setSelectLayout(viewTreeBean);
        propertiesAdapter.setData(viewTreeBean);
        layoutInfoView.setVisibility(View.VISIBLE);
        updateActionAble(viewTreeBean);
    }

    private void updateActionAble(ViewTreeBean bean) {
        if (bean != null) {
            ViewTreeBean parent = bean.getParentView();
            toParentViewBtn.setVisibility(parent == null ? View.INVISIBLE : View.VISIBLE);
            boolean isEmpty = bean.getChildView().isEmpty();
            toChildViewBtn.setVisibility(isEmpty ? View.INVISIBLE : View.VISIBLE);
        }
    }

    private boolean haveParentView(ViewTreeBean bean) {
        return bean.getParentView() != null;
    }

    @Override
    public void finish() {
        LayoutViewerObservable.getInstance().unRegisterNotify(observe);
        LayoutViewerObservable.getInstance().onLayoutViewerStatus(false);
        observe = null;
        DevelopToolsService.setScanLayout(this, false);
        super.finish();
    }

    private void doprintln(ViewTreeBean bean) {
//        if (bean != null) {
//            StringBuilder levelPre = new StringBuilder(">>>");
//            for (int i = 0; i < bean.layerLevel; i++) {
//                levelPre.append(">>>");
//            }
//            SnbLog.e(levelPre + "Id:" + bean.getViewIDName());
//            SnbLog.e(levelPre + "层级:" + bean.layerLevel);
//            SnbLog.e(levelPre + "父布局层级:" + bean.inParentLevel);
//            SnbLog.e(levelPre + "屏幕坐标:" + bean.inScreenLocation.toString());
//            SnbLog.e(levelPre + "父布局坐标:" + bean.inParentLocation.toString());
//            SnbLog.e(levelPre + "宽,高:" + bean.getWidth() + "," + bean.getHeight());
//            SnbLog.e(levelPre + "子布局:" + bean.childView.size());
//            for (ViewTreeBean childBean : bean.childView) {
//                doprintln(childBean);
//            }
//
//        }
    }
}
